package org.ponly.cta4j.factory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.ponly.cta4j.CaptchaFactory;

/**
 * 组合验证码工厂.
 *
 * @author vacoor
 * @since 1.0
 */
public class CompositeCaptchaFactory extends ProxiedCaptchaFactory {
    /**
     * random for factories.
     */
    private Random random = new Random();

    /**
     * factories.
     */
    private List<CaptchaFactory> factories = new ArrayList<>();

    /**
     * 创建一个组合工厂, 并使用给定 factories 初始化.
     *
     * @param factories 验证码工厂
     */
    public CompositeCaptchaFactory(final CaptchaFactory... factories) {
        addFactories(factories);
    }

    /**
     * 创建一个组合工厂, 并使用给定 factories 初始化.
     *
     * @param factories 验证码工厂
     */
    public CompositeCaptchaFactory(final List<CaptchaFactory> factories) {
        this.factories.addAll(factories);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected CaptchaFactory getCaptchaFactory() {
        return 0 < factories.size() ? factories.get(random.nextInt(factories.size())) : null;
    }

    /**
     * 添加验证码工厂.
     *
     * @param factories 验证码工厂
     * @return 当前实例
     */
    public CompositeCaptchaFactory addFactories(final CaptchaFactory... factories) {
        Collections.addAll(this.factories, factories);
        return this;
    }

    /**
     * 添加验证码工厂.
     *
     * @param factories 验证码工厂
     * @return 当前实例
     */
    public CompositeCaptchaFactory addFactories(final Iterable<CaptchaFactory> factories) {
        for (final CaptchaFactory factory : factories) {
            this.factories.add(factory);
        }
        return this;
    }
}
